package org.layuiframework.generator.engine;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.layuiframework.generator.config.po.LayuiTableInfo;
import org.layuiframework.generator.util.FileUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class LayuiTableInfoLoader {

    private Map<String, LayuiTableInfo> CACHES = new ConcurrentHashMap<>();

    private LayuiTableInfoLoader () {}

    public static boolean init(String filePath){
        return readFile(filePath);
    }

    public static Map<String, LayuiTableInfo> get(){
        return Singleton.getInstance().CACHES;
    }

    public static boolean destroy(String filePath){
        ObjectMapper mapper=new ObjectMapper();
        try {
            String content = mapper.writeValueAsString(Singleton.getInstance().CACHES);
            FileUtil.writeString(filePath, content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Singleton.getInstance().CACHES.clear();
        return true;
    }

    private static boolean readFile(String filePath){
        File file = new File(filePath);
        if(!file.exists()) return false;
        String content = FileUtil.readString(filePath);
        ObjectMapper mapper = new ObjectMapper();
        try {
            Singleton.getInstance().CACHES = mapper.readValue(content, TypeFactory.defaultInstance().constructMapType(ConcurrentHashMap.class, String.class, LayuiTableInfo.class));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private static class Singleton{

        private static LayuiTableInfoLoader singleton;

        private static LayuiTableInfoLoader getInstance(){

            if(null == singleton){
                singleton = new LayuiTableInfoLoader();
            }
            return singleton;

        }
    }

}
